<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/3
 * Time: 16:18
 */

namespace app\home\controller;

use app\api\model\ClassroomType as ClassroomTypeModel;//课程分类
use app\api\model\Classroom as ClassroomModel;//课程
use app\api\model\ClassroomCatalogue as ClassroomCatalogueModel;//课程章节
use app\api\model\ClassroomUser as ClassroomUserModel;//购买课程
use app\api\model\MyClassroom as MyClassroomModel;//我的收藏
use app\api\model\ClassroomComment as ClassroomCommentModel;//评论
use app\api\model\ClassroomHistory as ClassroomHistoryModel;//观看历史
use app\api\model\AboutUs as AboutUsModel;//关于我们
use think\Config;
use think\Db;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use org\Qiniu;

class Classroom extends Common
{
    /**
     * 课程列表
     */
    public function index(){
        session('target_url',"http://south.xuanwumobile.com/home/Classroom/index");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $where['classroom_status'] = 2;
        //课程分类、ID
        $classroomTypeModel = new ClassroomTypeModel();
        $type = $classroomTypeModel->getClassroomType();
        //课程列表
        $field = 'id, classroom_title, classroom_price, classroom_img, classroom_cate';
        $lists = Db::table('up_classroom')
            ->field($field)
            ->where($where)
            ->order('classroom_sort desc')
            ->limit(0, 10)
            ->select();
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        foreach($lists as &$list) {
            $num = $classroomCatalogue->countNum($list['id']);
            $list['num'] = $num;
        }
        //收费开关
        $price_button = Db::table('up_about_us')->where('id', 1)->value('price_button');
        //todo:需要将user_id传到html页面
        $this->assign([
            'type' => $type,
            'lists' => $lists,
            'price_button' => $price_button,
            'user_id' => session('u_openid')
//            'user_id' => 127
        ]);
        return $this->fetch();
    }
    
    /**
     * ajax加载课程列表
     * page：当前页码
     * classroomType：课程分类ID  默认为-1，表示全部
     * order：排序规则  默认为1    1综合  2最热  3最新  4价格
     * orderP：价格排序规则   当order值为4时，需要该参数，默认值为1   1价格升序  2价格降序
     */
    public function ajaxIndex()
    {
        $params = input('param.');
        $where = [];
        //课程列表
        $field = 'id, classroom_title, classroom_price, classroom_img, classroom_cate';
        
        if(isset($params['classroomType']) && $params['classroomType'] != -1) {
            $where ['classroom_id'] = $params['classroomType'];//课堂分类
        }
        $order = 'classroom_sort desc';
        if(isset($params['order'])){
            if($params['order'] == 1) {//综合排序
                $order = 'classroom_sort desc';
            } elseif($params['order'] == 2) {//最热排序
                $order = 'classroom_playnum desc';
            } elseif($params['order'] == 3) {//最新排序
                $order = 'create_time desc';
            } elseif($params['order'] == 4) {//价格排序
                if($params['orderP'] == 1) {//价格升序
                    $order = 'classroom_price, classroom_playnum desc';
                } elseif($params['orderP'] == 2) {//价格降序
                    $order = 'classroom_price desc, classroom_playnum desc';
                }
            }
        }
        $classroomModel = new ClassroomModel();
        $lists = $classroomModel->getClasssroomList($field, $where, $order, $params['page'], 10);
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        foreach($lists as &$list) {
            $num = $classroomCatalogue->countNum($list['id']);
            $list['num'] = $num;
        }
        //收费开关
        $price_button = Db::table('up_about_us')->where('id', 1)->value('price_button');
        return json(['status'=>200, 'msg'=>$lists, 'price_button'=>$price_button]);
    }
    
    /**
     * ajax上拉/下拉加载课程列表
     * page：当前页码
     * classroomType：课程分类ID  默认为-1，表示全部
     * order：排序规则  默认为1    1综合  2最热  3最新  4价格
     * orderP：价格排序规则   当order值为4时，需要该参数，默认值为1   1价格升序  2价格降序
     */
    public function ajaxIndexE()
    {
        $params = input('param.');
        $where = [];
        //课程列表
        $field = 'id, classroom_title, classroom_price, classroom_img, classroom_cate';
        
        if(isset($params['classroomType']) && $params['classroomType'] != -1) {
            $where ['classroom_id'] = $params['classroomType'];//课堂分类
        }
        $order = 'classroom_sort desc';
        if(isset($params['order'])){
            if($params['order'] == 1) {//综合排序
                $order = 'classroom_sort desc';
            } elseif($params['order'] == 2) {//最热排序
                $order = 'classroom_playnum desc';
            } elseif($params['order'] == 3) {//最新排序
                $order = 'create_time desc';
            } elseif($params['order'] == 4) {//价格排序
                if($params['orderP'] == 1) {//价格升序
                    $order = 'classroom_price, classroom_playnum desc';
                } elseif($params['orderP'] == 2) {//价格降序
                    $order = 'classroom_price desc, classroom_playnum desc';
                }
            }
        }
        $classroomModel = new ClassroomModel();
        $lists = $classroomModel->getClasssroomList($field, $where, $order, $params['page'], 10);
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        foreach($lists as &$list) {
            $num = $classroomCatalogue->countNum($list['id']);
            $list['num'] = $num;
        }
        //收费开关
        $price_button = Db::table('up_about_us')->where('id', 1)->value('price_button');
        return json(['status'=>200, 'msg'=>$lists, 'price_button'=>$price_button]);
    }
    
    /******************** 课程详情 start ********************/
    
    /**
     * 课程基本信息
     * classroom_cata：课程类型   1 免费课程  2 付费课程
     * classroom_id：课程ID
     */
    public function classroomInfo()
    {
        header("Access-Control-Allow-Origin:*");
        //TODO:user_id
        $params = input('param.');
        $user_id = $params['user_id'];
        $aboutUsModel = new AboutUsModel();
        $field = 'price_button';
        $price_button = $aboutUsModel->getField($field);
        if($price_button['price_button'] == 1){//如果价格不隐藏，则判断课程是否是付费课程
            $classroom_cate = Db::table('up_classroom')->where('id', $params['classroom_id'])->value('classroom_cate');
            if($classroom_cate == 2) {//如果是付费课程，判断该用户有没有购买
                $classroomuserModel = new ClassroomUserModel();
                $res = $classroomuserModel->ifBuy($params['classroom_id'], $user_id);
                if(! $res){
                    return $this->apiError(4003);
                }
            }
        }
        
        $classroomModel = new ClassroomModel();
        $classroomModel->playSort($params['classroom_id']);//播放量加1&排序加2
        $field = 'id, classroom_playnum, classroom_title, classroom_price';
        $classroomInfo = $classroomModel->getClassroomInfo($field, $params['classroom_id']);
        //是否收藏
        $collection = 1;//已收藏
        $myClassroomModel = new MyClassroomModel();
        $result = $myClassroomModel->ifCollection($params['classroom_id'], $user_id);
        if(!$result){
            $collection = 2;//未收藏
        }
        $classroomInfo['collection'] = $collection;
        return $this->apiSuccess($classroomInfo);
    }
    
    /**
     * 评论列表
     * page：当前页码
     * classroom_id：课程ID
     */
    public function classroomComment(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $user_id = $params['user_id'];
        //该课程所有评论
        $page = $params['page']?$params['page']:1;
        $pageNum = $page - 1;
        $field = 'c.comment_id, c.comment_content, c.comment_img,
        c.create_time, c.classroom_id, c.like_num, uuu.user_username, uuu.user_image, uuu.user_id';
        $lists = Db::table('up_classroom_comment')->alias('c')
            ->field($field)
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('comment_type', 1)
            ->where('c.classroom_id', $params['classroom_id'])
            ->order('c.create_time desc')
            ->limit($pageNum * 10, 10)
            ->select();
        //评论下的所有回复
        $field1 = 'c.comment_id, c.comment_content, c.parent_id, c.classroom_id, 
        c.like_num, uuu.user_username, uuu.user_id';
        $classroomCommentModel = new ClassroomCommentModel();
        $replyLists = $classroomCommentModel->getReplyLists($field1, $params['classroom_id']);
        //回复是否被该用户收藏
        foreach($replyLists as $key=>&$replyList){
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $user_id)
                ->where('data_id', $replyList['comment_id'])
                ->find();
            if($res){
                $replyList['like'] = 1;
            }else{
                $replyList['like'] = 2;
            }
        }
        //评论是否被该用户收藏
        foreach($lists as $k=>&$vo){
            if(!empty($vo['comment_img'])){
                $co_img = trim($vo['comment_img'], ',');
                $vo['comment_img'] = explode(',', $co_img);
            }else{
                $vo['comment_img'] = [];
            }
         
            $res = Db::table('up_dz')
                ->where('type', 7)
                ->where('user_id', $user_id)
                ->where('data_id', $vo['comment_id'])
                ->find();
            if($res){
                $vo['like'] = 1;
            }else{
                $vo['like'] = 2;
            }
    
            $start_time = date('Ymd',strtotime($vo['create_time']));
            if($start_time==date('Ymd',time())){//同年同月同日
                $vo['create_time'] = date('m-d',strtotime($vo['create_time'])).'   '.date('H:i',strtotime($vo['create_time']));
            }elseif (date('Y',strtotime($vo['create_time']))!=date('Y',time())){
                //不同年
                $vo['create_time'] = date('Y-m-d',strtotime($vo['create_time'])).'  '.date('H:i',strtotime($vo['create_time']));
            }else{
                $vo['create_time'] = date('m-d',strtotime($vo['create_time'])).'  '.date('H:i',strtotime($vo['create_time']));
            } 
        }
//        foreach($lists as $key=>&$list){
//            if(!empty($vo['comment_img'])){
//                $vo['comment_img'] = explode(',', $vo['comment_img']);
//            }else{
//                $vo['comment_img'] = [];
//            }
//            $res = Db::table('up_dz')
//                ->where('type', 7)
//                ->where('user_id', $params['user_id'])
//                ->where('data_id', $list['comment_id'])
//                ->find();
//            if($res){
//                $list['like'] = 1;
//            }else{
//                $list['like'] = 2;
//            }
//        }
        //评论下的所有回复
        foreach($lists as $key=>&$list){
           
            $list['son'] = [];
            $list['sonNum'] = 0;
            for($i=0; $i<count($replyLists); $i++){
                if($list['comment_id'] == $replyLists[$i]['parent_id']){
                    $list['son'][] = $replyLists[$i];
                }
            }
            $list['sonNum'] = count($list['son']);//该评论下回复的数量
        }
        //所有评论数
        $num = Db::table('up_classroom_comment')
            ->where('comment_type', 1)
            ->where('classroom_id', $params['classroom_id'])
            ->count();
        return json_encode(['status'=>200, 'msg'=>'成功', 'num'=>$num, 'data'=>$lists], 256);
    }
    
    /**
     * 课程的详细信息
     * classroom_id：课程ID
     */
    public function classroomDetail(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $field = 'classroom_content';
        $classroomModel = new ClassroomModel();
        $classroomDetail = $classroomModel->getClassroomInfo($field, $params['classroom_id']);
        return $this->apiSuccess($classroomDetail);
    }
    
    /**
     * 课程目录
     * @return string
     * classroom_id：课程ID
     */
    public function catalogue(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        //课程章节
        $classroomCatalogue = new ClassroomCatalogueModel();
        $num = $classroomCatalogue->countNum($params['classroom_id']);
        //目录
        $field = 'catalogue_id, catalogue_img, catalogue_url, catalogue_title, catalogue_time';
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        $list = $classroomCatalogueModel->catalogueLists($field, $params['classroom_id']);
        return json_encode(['status'=>200, 'msg'=>'成功', 'num'=>$num, 'data'=>$list], 256);
    }
    
    /******************** 课程详情 end ********************/
    /******************** 删除评论/回复 start ********************/
    
    /**
     * 删除评论
     * comment_id：被删除的评论或回复ID
     * classroom_id：被删除评论/回复的课程ID
     * type：被删除的是评论还回复   1评论   2回复
     */
    public function delComment(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $classroomCommentModel = new ClassroomCommentModel();

//        $user_id = $classroomCommentModel->getUserIDByCommentID($params['comment_id']);
//        if($user_id != $params['user_id']){//如果发布评论的用户ID和当前用户ID不一样，则不允许删除
//            return $this->apiError('E134');
//        }
        
        $ids = $classroomCommentModel->getReplyByComment($params['comment_id']);//根据评论ID获取该评论下所有回复ID
//        $classroom_id = $classroomCommentModel->getClassroomID($params['comment_id']);
        
        if($params['type'] == 1){//删除评论
            //1删除点赞表中该评论的所有点赞记录 2排序字段减对应数量 3删除评论表中的记录
            if(empty($ids)){//评论下无回复
                $this->doDelComment(7, $params, 1);
            }else{
                //删除点赞表中该评论及该评论下所有回复
                Db::table('up_dz')
                    ->where(function ($query) use($params){
                        $query->where('data_id', $params['comment_id'])->where('type', 7);
                    })
                    ->whereOr(function ($query1) use($ids){
                        $query1->where('data_id', 'IN', $ids)->where('type', 8);
                    })
                    ->delete();
                $num = count($ids) + 1;//回复+评论数量
                $this->doDel($params, $num, $ids);
//                Db::table('up_classroom_comment')->where('comment_id', $params['comment_id'])->delete();
            }
        }else{//删除回复
            $this->doDelComment(8, $params, 1);
        }
        return $this->apiSuccess();
    }
    
    /**
     * 1删除点赞表中该评论的所有点赞记录 2排序字段减对应数量 3删除评论表中的记录
     * @param $type  删除的收藏类型  7评论  8回复
     * @param $params 前度传递的参数
     * @param $num  排序字段减少的数组
     */
    protected function doDelComment($type, $params, $num){
        header("Access-Control-Allow-Origin:*");
        //删除点赞表中该评论
        Db::table('up_dz')
            ->where('data_id', $params['comment_id'])
            ->where('type', $type)
            ->delete();
        $this->doDel($params, $num);
    }
    
    /**
     * 删除评论时 排序字段减少相应数值，删除该条评论/回复
     * @param $params  前端传递的参数
     * @param $num  被删除的数字
     * @param string $ids  评论下所有回复ID
     */
    protected function doDel($params, $num, $ids = ''){
        header("Access-Control-Allow-Origin:*");
        $classroomCommentModel = new ClassroomCommentModel();
        $classroomModel = new ClassroomModel();
        $classroomModel->commentSort(2, $params['classroom_id'], $num);//排序字段减$num
        $classroomCommentModel->delComment($params['comment_id'], $ids);//删除该条评论
    }
    
    /******************** 删除评论/回复 end ********************/
    
    /**
     * 视频播放地址
     * classroom_id：课程ID
     * catalogue_id：目录ID
     */
    public function videoUrl(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        //目录ID错误
        $res = $classroomCatalogueModel->getUrl('', $params['catalogue_id']);
        if(!$res){
            return $this->apiError(4004);
        }
        
        if($params['catalogue_id'] == ''){//首次进入页面时，默认显示第一节
            $url = $classroomCatalogueModel->getUrl($params['classroom_id']);
        }else{
            $field = 'catalogue_id, catalogue_url';
            $url = $classroomCatalogueModel->getUrl('', $params['catalogue_id'], $field);
        }
        return $this->apiSuccess($url);
    }
    
    /**
     * 我的收藏/取消收藏
     * collect：收藏状态  1已收藏，点击取消收藏   2未收藏，点击收藏
     * classroom_id：课程ID
     * catalogue_id：章节ID
     */
    public function myCollect(){
        header("Access-Control-Allow-Origin:*");
        //todo:user_id
        $params = input('param.');
//        $user_id = session('u_openid');
        $user_id = $params['user_id'];
        $classroomModel = new ClassroomModel();
        $myClassroomModel = new MyClassroomModel();
        $result = $myClassroomModel->ifCollection($params['classroom_id'], $user_id);
        if($result){//已收藏的，点击取消收藏
            $resD = $myClassroomModel->delCollect($params['classroom_id'], $user_id);
            if(!$resD){//删除记录失败
                return $this->apiError(4005);
            }
            $classroomModel->collectSort(2, $params['classroom_id']);//排序字段减1
            $collect = 2;
        }else{//未收藏，点击添加收藏
            $data = $this->playProgress($params);
            $resA = $myClassroomModel->addCollect($data);
            if(!$resA){//添加收藏失败
                return $this->apiError(4005);
            }
            $classroomModel->collectSort(1, $params['classroom_id']);//排序字段加1
            $collect = 1;
        }
        return $this->apiSuccess(['collect'=>$collect,'user_id'=>$user_id]);
    }
    
    /**
     * 更新收藏记录
     * classroom_id：课程ID
     * catalogue_id：目录ID
     * 用户已经收藏了该课程，点击目录列表，更换目录时调用
     */
    public function updateCollect(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
//        $user_id = session('u_openid');
        $user_id = $params['user_id'];
        $myClassroomModel = new MyClassroomModel();
        $data = $this->playProgress($params);
        $field = 'id, catalogue_id';
        $myCollect = $myClassroomModel->ifCollection($params['classroom_id'], $user_id, $field);
        $myClassroomModel->updateCollect($myCollect['id'], $data);
        return $this->apiSuccess();
    }
    
    /**
     * 购买课程页面
     * @return mixed
     */
    public function pay(){
        $classroom_id = input('param.classroom_id');
        session('target_url',"http://south.xuanwumobile.com/home/Classroom/pay?classroom_id={$classroom_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $info = Db::table('up_classroom')->where('id', $classroom_id)->find();
        $this->assign('info', $info);
        return $this->fetch();
    }
    
    /**
     * 写评论页面
     * @return mixed
     */
    public function writePL(){
        $classroom_id = input('param.classroom_id');
        session('target_url',"http://south.xuanwumobile.com/home/Classroom/writePL?classroom_id={$classroom_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $user_id = session('u_openid');
        //微信
        $options = Config::get('wechat');
        $app = new Application($options);
        $js = $app->js;
        $json = $js->config(array('getLocation','chooseImage','uploadImage','downloadImage','getLocalImgData'), false ,false,true);
        $this->assign(['json'=>$json,'uid'=>input('uid')]);
        $this->assign('classroom_id',$classroom_id);
        //todo:需要将user_id传到html页面
        $this->assign('user_id', $user_id);
        return $this->fetch();
    }
    
    /**
     * 添加评论
     */
    public function createPL(){
        header("Access-Control-Allow-Origin:*");
        //todo: 缺少用户ID
        
//        extract(input());
        $params = input('param.');
//        $user_id = session('u_openid');
        $user_id = $params['user_id'];
        $up = new Qiniu();
        $arr = '';
        if(isset($params['photo'])){
            foreach($params['photo'] as $key=>$vo){
                $img = base64_img1($vo)['msg'];
                //取出图片后缀
                $type = explode(".",$img);
                $type = end($type);
                //组装图片名
                $key = md5(time().uuid()).'.'.$type;
                $arr[] = $up->uploadFile($img,$key,'http://qiniu.verynurse.com/');
                unlink($img);
            }
            $arr = implode (',',$arr).',';
        }
        $data = [
            'parent_id' => 0,//评论或回复的父级ID，评论时为0
            'comment_type' => 1,//分类  1评论  2回复
            'classroom_id' => $params['classroom_id'],//课程ID
            'comment_content' => $params['content'],//评论内容
            'comment_user' => $user_id,//发布评论的人
            'create_time' => date('Y-m-d H:i:s'),//发布评论的人
            'comment_img' => $arr,//评论的图片
        ];
    
        $classroomCommentModel = new ClassroomCommentModel();
        $res = $classroomCommentModel->createComment($data);
        if($res){
            $classroomModel = new ClassroomModel();
            $classroomModel->commentSort(1, $params['classroom_id']);
            return json(['code'=>200,'msg'=>$arr]);
        }else{
            return json(['code'=>100,'msg'=>'评论失败']);
        }
    }
    
    /**
     * 添加回复
     * content：发布的内容
     * classroom_id：课程ID
     * comment_type：1评论课程  2回复评论
     * comment_id：评论的ID  当comment_type为2时，传此值
     */
    public function createHF(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        //TODO:user_id
        $user_id = $params['user_id'];
        $content = trim($params['content'],' ');//评论内容
        $data = [
            'parent_id' => $params['comment_id'],//评论或回复的父级ID，回复时为回复的评论ID
            'comment_type' => 2,//分类  1评论  2回复
            'classroom_id' => $params['classroom_id'],//课程ID
            'comment_content' => $content,//评论内容
            'comment_user' => $user_id,//发布评论的人
            'create_time' => date('Y-m-d H:i:s'),//发布评论的人
        ];
        
        $classroomCommentModel = new ClassroomCommentModel();
        $res = $classroomCommentModel->createComment($data);
        if(!$res){
            return $this->apiError('K100');
        }else{
            $classroomModel = new ClassroomModel();
            $classroomModel->commentSort(1, $params['classroom_id']);
            return $this->apiSuccess();
        }
    }
    
    /**
     * 查看全部回复
     */
    public function allComment(){
        header("Access-Control-Allow-Origin:*");
        $comment_id = input('param.comment_id');
        session('target_url',"http://south.xuanwumobile.com/home/Classroom/allComment?comment_id={$comment_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        //TODO:user_id需要传到html页面
        $user_id = session('u_openid');
//        print_r($params);die;
        $field = 'c.comment_id, c.comment_content, c.comment_img, c.comment_user, 
        c.create_time, c.classroom_id, c.like_num, uuu.user_username, uuu.user_image, uuu.user_id';
        //评论详情
        $oneComment = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.comment_id', $comment_id)
            ->field($field)
            ->find();
        $day = date('Y-m-d',time());//当前时间
        $time = time() - 3600*24;//昨天的时间戳
        $last_time = date('Y-m-d 00:00:00',$time);//昨天开始
        $last_time1 = date('Y-m-d 23:59:59',$time);//昨天结束
        if($day==date('Y-m-d',strtotime($oneComment['create_time']))){//判断是否是今天
            $oneComment['create_time'] ='今天'.' '.date('H:i',strtotime($oneComment['create_time']));
        }elseif ($last_time<$oneComment['create_time']&&$oneComment['create_time']<$last_time1)
        {//判断是否是昨天
            $oneComment['create_time'] ='昨天'.' '.date('m-d H:i',strtotime($oneComment['create_time']));
        }
        //单条评论下所有回复
        $replys = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.parent_id', $comment_id)
            ->field($field)
            ->limit(0, 10)
            ->order('c.create_time desc')
            ->select();
        $replysConun = Db::table('up_classroom_comment')
            ->alias('c')
            ->where('c.parent_id', $comment_id)
            ->select();
        $sonNum = count($replysConun);//单条评论下的所有回复数量
        $oneComment['sonNum'] = $sonNum;
        //评论是否被该用户点赞
        $resC = Db::table('up_dz')
            ->where('type', 7)
            ->where('user_id', $user_id)
            ->where('data_id', $oneComment['comment_id'])
            ->find();
        if($resC){
            $oneComment['like'] = 1;
        }else{
            $oneComment['like'] = 2;
        }
        //转换图片为数组

        $aa = explode(',',trim($oneComment['comment_img'],','));
        if(count(array_filter($aa))>0){
            $oneComment['comment_img'] = $aa;
        }else{
            $oneComment['comment_img'] = array();
        }
        //回复是否被该用户点赞
        foreach($replys as $key=>&$reply){
            //转换图片为数组
            if(!empty($reply['comment_img'])){
                $reply['comment_img'] = explode(',', $reply['comment_img']);
            }else{
                $reply['comment_img'] = [];
            }
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $user_id)
                ->where('data_id', $reply['comment_id'])
                ->find();
            if($res){
                $reply['like'] = 1;
            }else{
                $reply['like'] = 2;
            }
            if($day==date('Y-m-d',strtotime($reply['create_time']))){//判断是否是今天
                $reply['create_time'] ='今天'.' '.date('H:i',strtotime($reply['create_time']));
            }elseif ($last_time<$reply['create_time']&&$reply['create_time']<$last_time1)
            {//判断是否是昨天
                $reply['create_time'] ='昨天'.' '.date('m-d H:i',strtotime($reply['create_time']));
            }
        }
        $oneComment['son'] = $replys;
        $this->assign([
           'oneComment' => $oneComment,
            'user_id' => $user_id,
            'comment_id' => $comment_id
        ]);
        return $this->fetch();
    }
    
    /**
     * ajax上拉/下拉刷新数据
     * 查看全部回复
     */
    public function ajaxAllComment(){
        header("Access-Control-Allow-Origin:*");
//        session('target_url',"http://south.xuanwumobile.com/home/Classroom/index");
//        $openid = $this->getOpenid();
//        $this->getUserId($openid);
//        //TODO:user_id需要传到html页面
//        $user_id = session('u_openid');
        $comment_id = input('param.comment_id');
        $page = input('param.page');
        $user_id = input('param.user_id');
        $field = 'c.comment_id, c.comment_content, c.comment_img, c.comment_user, 
        c.create_time, c.classroom_id, c.like_num, uuu.user_username, uuu.user_image, uuu.user_id';
        
        //单条评论下所有回复
        $replys = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.parent_id', $comment_id)
            ->field($field)
            ->limit(($page - 1) * 10, 10)
            ->order('c.create_time desc')
            ->select();
        $day = date('Y-m-d',time());//当前时间
        $time = time() - 3600*24;//昨天的时间戳
        $last_time = date('Y-m-d 00:00:00',$time);//昨天开始
        $last_time1 = date('Y-m-d 23:59:59',$time);//昨天结束
        //回复是否被该用户点赞
        foreach($replys as $key=>&$reply){
            if($reply['comment_user'] == $user_id){
                $reply['user_del'] = 1;
            }else{
                $reply['user_del'] =0;
            }
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $user_id)
                ->where('data_id', $reply['comment_id'])
                ->find();
            if($res){
                $reply['like'] = 1;
            }else{
                $reply['like'] = 2;
            }
            if($day==date('Y-m-d',strtotime($reply['create_time']))){//判断是否是今天
                $reply['create_time'] ='今天'.' '.date('H:i',strtotime($reply['create_time']));
            }elseif ($last_time<$reply['create_time']&&$reply['create_time']<$last_time1)
            {//判断是否是昨天
                $reply['create_time'] ='昨天'.' '.date('m-d H:i',strtotime($reply['create_time']));
            }
        }
        return json(['status'=>200, 'msg'=>$replys]);
    }
    
    /******************** 课程详情点赞 start ********************/
    /**
     * 点赞/取消点赞
     * type：点赞类型     1点赞评论    2点赞回复
     * comment_id：点赞的评论/回复ID
     * like：是否点赞   1已点赞，点击取消点赞     2未点赞，点击点赞
     */
    public function likeComment(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['user_id'] == 0){
            return $this->apiError(4007);
        }
        if($params['type'] == 1){//点赞评论
            $like = $this->doLike(7, $params);
        }else{//点赞回复
            $like = $this->doLike(8, $params);
        }
        return $this->apiSuccess(['like'=>$like]);
    }
    
    /**
     * 对点赞/取消点赞的操作
     * @param $type 类型  7点赞评论   8点赞回复
     * @param $params  前端传递的参数
     * @return int|void
     */
    protected function doLike($type, $params){
        header("Access-Control-Allow-Origin:*");
        $classroomCommentModel = new ClassroomCommentModel();
        $data = [
            'user_id' => $params['user_id'],
            'type' => $type,
            'data_id' => $params['comment_id']
        ];
        if($params['like'] == 1){//已点赞，点击取消点赞
            $res = Db::table('up_dz')
                ->where('data_id', $params['comment_id'])
                ->where('user_id', $params['user_id'])
                ->delete();
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(2, $params['comment_id']);//点赞量减1
            $like = 2;//未点赞
        }else{//未点赞，点击点赞
            //将数据插入点赞表
            $res = Db::table('up_dz')->insert($data);
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(1, $params['comment_id']);//点赞量加1
            
            $like = 1;//已点赞
        }
        return $like;
    }
    /******************** 课程详情点赞 end ********************/
    
    /******************** 全部回复点赞 start ********************/
    /**
     * 点赞/取消点赞
     * type：点赞类型     1点赞评论    2点赞回复
     * comment_id：点赞的评论/回复ID
     * like：是否点赞   1已点赞，点击取消点赞     2未点赞，点击点赞
     */
    public function likeComment1(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        if($params['type'] == 1){//点赞评论
            $like = $this->doLike1(7, $params);
        }else{//点赞回复
            $like = $this->doLike1(8, $params);
        }
        return $this->apiSuccess(['like'=>$like]);
    }
    
    /**
     * 对点赞/取消点赞的操作
     * @param $type 类型  7点赞评论   8点赞回复
     * @param $params  前端传递的参数
     * @return int|void
     */
    protected function doLike1($type, $params){
        header("Access-Control-Allow-Origin:*");
        //TODO:user_id
        $user_id = $params['user_id'];
        $classroomCommentModel = new ClassroomCommentModel();
        $data = [
            'user_id' => $user_id,
            'type' => $type,
            'data_id' => $params['comment_id']
        ];
        $where = [];
        $where['user_id'] = $user_id;
        $where['type'] = $type;
        $where['data_id'] = $params['comment_id'];
        $result = Db::table('up_dz')->where($where)->find();
        if($result){//已点赞，点击取消点赞
            $res = Db::table('up_dz')
                ->where('data_id', $params['comment_id'])
                ->where('user_id', $user_id)
                ->delete();
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(2, $params['comment_id']);//点赞量减1
            $like = 2;//未点赞
        }else{//未点赞，点击点赞
            //将数据插入点赞表
            $res = Db::table('up_dz')->insert($data);
            if(!$res){
                return $this->apiError(4005);
            }
            $classroomCommentModel->likeNum(1, $params['comment_id']);//点赞量加1
            
            $like = 1;//已点赞
        }
        return $like;
    }
    /******************** 全部回复点赞 end ********************/
    
    /**
     * 购买
     * @return int|\think\response\View
     */
    public function buy(){
        extract(input());
        if(!isset($classroom_id)){
            echo '参数错误！请从公众号进入！';
            die;
        }
        session('target_url',"http://south.xuanwumobile.com/home/Classroom/buy?classroom_id={$classroom_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $data = Db::table('up_classroom')->where('id',$classroom_id)->find();
        $number = date('YmdHis') . rand(1000000,9999999);
        $order = array();
        $order['order_number'] = $number;//订单编号
        $order['order_money'] = $data['classroom_price'];//订单价格
        $order['order_time'] = date('Y-m-d H:i:s');//订单创建时间
        $order['order_type'] = 2;//支付方式 1支付宝 2微信
        $order['order_status'] = 2;//订单状态
        $order['user_id'] = session('u_openid');//用户ID
        $order['classroom_id'] = $classroom_id;//购买的课程ID
        
        $res = Db::table('up_classroom_order')->insert($order);
        $too = '购买课程';
        if($res){
            //===================================================================================
            $options = Config::get('wechat');
            $options['payment']['notify_url'] ='http://south.xuanwumobile.com/home/Classroom/buyback';
            $app = new Application($options);
            $payment = $app->payment;
//            return $payment;
            //---------------------------2
            $openid_pay = session('openid_pay');
            $attributes = [
                'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
                'body'             => "$too",
                'detail'           => "$too",
                'out_trade_no'     => "$number",
                'total_fee'        => $data['classroom_price'] * 100, // 单位：分
                'notify_url'       => 'http://south.xuanwumobile.com/home/Classroom/buyback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
                'openid'           => "$openid_pay", // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
                // ...
            ];
            $order = new Order($attributes);
//            return $order;
            //--------------------------------3
            $result = $payment->prepare($order);
//            return ($result->return_msg);
            if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
                $prepayId = $result->prepay_id;
                $json = $payment->configForPayment($prepayId);
                return view('classroom/pay_done',['json'=>$json,'classroom_id'=>$classroom_id, 'user_id'=>session('u_openid')]);
            }else{
                return  1;
            }
        }else{
            return 2;
        }
    }
    
    public function buyback()
    {
        $options = Config::get('wechat');
        $options['payment']['notify_url'] ='http://south.xuanwumobile.com/home/Classroom/buyback';
        $app = new Application($options);
        $response = $app->payment->handleNotify(function($notify, $successful){
            // 使用通知里的 "微信支付订单号" 或者 "商户订单号" 去自己的数据库找到订单
//            $order = 查询订单($notify->out_trade_no);
            // 用户是否支付成功
            if ($successful) {
                Db::startTrans();
                try{
                    $trade_no =$notify->out_trade_no;
                    $order = Db::table('up_classroom_order')->where('order_number',$trade_no)->find();
                    $update = array();
                    $update['order_status'] = 1;//订单状态  1已完成
//                    $update['order_transaction_id'] = $notify['transaction_id'];//微信返回的订单号
                    $update['pay_time'] = $this->getDateBytimeDate("{$notify['time_end']}");
                    Db::table('up_classroom_order')->where('order_number',$trade_no)->update($update);
                    $data = [
                        'classroom_id' => $order['classroom_id'],//课程ID
                        'user_id' => $order['user_id'],//用户ID
                        'create_time' => $update['pay_time']
                    ];
                    Db::table('up_classroom_user')->insert($data);
                    Db::commit();
                    return true;
                }catch (\Exception $e) {
                    Db::rollback();
                    return 'database error';
                }
            } else { // 用户支付失败
                return 'pay false';
            }

//            return true; // 返回处理完成
        });
        $response->send();
    }
    
    /**
     * 收费功能开关
     */
    public function ifPrice(){
        header("Access-Control-Allow-Origin:*");
        $aboutUsModel = new AboutUsModel();
        $field = 'price_button';
        $content = $aboutUsModel->getField($field);
        return $this->apiSuccess($content);
    }
    
    
    
    
    
    
    
    
    
    
    
    /**
     * 获取回复详情
     * comment_id：评论ID
     */
    public function commentDetail(){
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $field = 'c.comment_id, c.comment_content, c.create_time, c.classroom_id, c.like_num, uuu.user_username, uuu.user_image';
        //评论详情
        $oneComment = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.comment_id', $params['comment_id'])
            ->field($field)
            ->find();
        //单条评论下所有回复
        $replys = Db::table('up_classroom_comment')
            ->alias('c')
            ->join('up_u_user uuu', 'uuu.user_id = c.comment_user', 'left')
            ->where('c.parent_id', $params['comment_id'])
            ->field($field)
            ->order('c.create_time desc')
            ->select();
        $sonNum = count($replys);//单条评论下的所有回复数量
        $oneComment['sonNum'] = $sonNum;
        //评论是否被该用户点赞
        $resC = Db::table('up_dz')
            ->where('type', 7)
            ->where('user_id', $params['user_id'])
            ->where('data_id', $oneComment['comment_id'])
            ->find();
        if($resC){
            $oneComment['like'] = 1;
        }else{
            $oneComment['like'] = 1;
        }
        //转换图片为数组
        if(!empty($oneComment['comment_img'])){
            $oneComment['comment_img'] = explode(',', $oneComment['comment_img']);
        }else{
            $oneComment['comment_img'] = [];
        }
        //回复是否被该用户点赞
        foreach($replys as $key=>&$reply){
            //转换图片为数组
            if(!empty($reply['comment_img'])){
                $reply['comment_img'] = explode(',', $reply['comment_img']);
            }else{
                $reply['comment_img'] = [];
            }
            $res = Db::table('up_dz')
                ->where('type', 8)
                ->where('user_id', $params['user_id'])
                ->where('data_id', $reply['comment_id'])
                ->find();
            if($res){
                $reply['like'] = 1;
            }else{
                $reply['like'] = 2;
            }
        }
        $oneComment['son'] = $replys;
        return $this->apiSuccess($oneComment);
    }
    
    /**
     * 历史   用户进入课程&用户点击目录时调用
     * classroom_id：课程ID
     * catalogue_id：目录ID  首次加载时，此值传空   默认此课程的第一章节
     */
    public function history(){
        header("Access-Control-Allow-Origin:*");
        //todo:user_id
        $params = input('param.');
        $data = $this->playProgress($params);
        $classroomHistoryModel = new ClassroomHistoryModel();
        $field = 'history_id, catalogue_id';
        $historyInfo = $classroomHistoryModel->getHistoryInfo($params['user_id'], $params['classroom_id'], $field);
        if(!$historyInfo){
            $classroomHistoryModel->createHistory($data);//没有观看历史，先添加记录
        }else{
            $classroomHistoryModel->updateHistory($historyInfo['history_id'], $data);
        }
        return $this->apiSuccess();
    }
    
    /**
     * 获取课程分类ID、名称
     */
    public function classroomType()
    {
        header("Access-Control-Allow-Origin:*");
        $params = input('param.');
        $classroomTypeModel = new ClassroomTypeModel();
        $type = $classroomTypeModel->getClassroomType();
        return $this->apiSuccess($type);
    }
    
    /**
     * 课程的详细信息
     * classroom_id：课程ID
     */
    public function classroomDetail1(){
        $params = input('param.');
        
        $field = 'classroom_content';
        $classroomModel = new ClassroomModel();
        $classroomDetail = $classroomModel->getClassroomInfo($field, $params['classroom_id']);
        return $this->apiSuccess($classroomDetail);
    }
    
    /**
     * 观看进度
     * @param $params  前端传递的数据
     * @return array
     */
    protected function playProgress($params){
//        header("Access-Control-Allow-Origin:*");
        $data = [
            'user_id' => $params['user_id'],//用户ID
            'classroom_id' => $params['classroom_id'],//课程ID
            'classroom_num' => 0,//该课程下所有章节数
            'catalogue_id' => 0,//目录ID
            'catalogue_num' => 0,//用户点击的章节在章节目录中的位置，第几章节
            'classroom_progress' => 0,//播放进度
            'create_time' => date('Y-m-d H:i:s')//观看时间
        ];
        $data['classroom_num'] = count($this->getCatalogueIDS($params['classroom_id']));
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        if($params['catalogue_id'] == ''){//首次进入页面时，默认显示第一节
            $catalogue = $classroomCatalogueModel->getUrl($params['classroom_id'])->toArray();
            $data['catalogue_id'] = $catalogue['catalogue_id'];
        }else{
            $data['catalogue_id'] = $params['catalogue_id'];
        }
        $data['catalogue_num'] = array_search($data['catalogue_id'], $this->getCatalogueIDS($params['classroom_id'])) + 1;
        if($data['classroom_num'] == 0){
            $data['classroom_progress'] = 0 . "%";
        }else{
            $data['classroom_progress'] = number_format($data['catalogue_num']/$data['classroom_num'], 4) * 100 . "%";
        }
        return $data;
    }
    
    /**
     * 根据课程ID ，获取该课程下所有目录的ID
     * @param $classroom_id 课程ID
     * @return array 
     */
    protected function getCatalogueIDS($classroom_id){
        header("Access-Control-Allow-Origin:*");
        $classroomCatalogueModel = new ClassroomCatalogueModel();
        $ids = $classroomCatalogueModel->catalogueIDList($classroom_id);
        return $ids;
    }
    
}